package controllers

import (
	"encoding/json"
	beego "github.com/beego/beego/v2/server/web"
	"shop/models"
	"strconv"
	"strings"
	"time"
)

type ShopController struct {
	beego.Controller
}
type JsonR struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

func (c *ShopController) Get() {
}
func (c *ShopController) Add() {
	file, header, err := c.GetFile("img")
	defer file.Close()
	if err != nil {
		res := JsonR{
			Code: 1,
			Msg:  "图片未上传,请上传图片",
			Data: nil,
		}
		c.Data["json"] = res
		c.ServeJSON()
		return
	}
	path := "static/img/" + header.Filename
	if header.Size >= 2*1024*1024 {
		res := JsonR{
			Code: 1,
			Msg:  "图片大小不能超过2MB,请重新上传",
			Data: nil,
		}
		c.Data["json"] = res
		c.ServeJSON()
		return
	}
	sufixx := header.Filename[strings.LastIndex(header.Filename, ".")+1:]
	if sufixx != "png" && sufixx != "jpg" {
		res := JsonR{
			Code: 1,
			Msg:  "图片格式不正确",
			Data: nil,
		}
		c.Data["json"] = res
		c.ServeJSON()
		return
	}
	c.SaveToFile("img", path)

	name := c.GetString("name")
	price, _ := c.GetFloat("price")
	info := c.GetString("info")
	shop := models.Shop{
		Name:  name,
		Price: price,
		Img:   "http://127.0.0.1:8080/" + path,
		Info:  info,
	}
	err = models.DB.Debug().Create(&shop).Error
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 0,
			Msg:  "添加失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "添加成功",
			Data: nil,
		}
		c.ServeJSON()
	}
}
func (c *ShopController) List() {
	page, _ := c.GetInt("page", 1)
	size, _ := c.GetInt("size", 5)
	query := models.DB.Debug().Model(&models.Shop{})
	name := c.GetString("name")
	if name != "" {
		query = query.Where("name like ?", "%"+name+"%")
	}
	key := "page-" + strconv.Itoa(page) + "-" + name
	val, err := models.RDb.Get(key).Result()
	pageData := make(map[string]interface{})
	if err != nil {
		var count int64
		query.Count(&count)
		offset := (page - 1) * size
		var shops []models.Shop
		err = query.Offset(offset).Limit(size).Find(&shops).Error
		if err != nil {
			c.Data["json"] = JsonR{
				Code: 0,
				Msg:  "查询失败",
				Data: nil,
			}
			c.ServeJSON()
		} else {

			pageData["count"] = count
			pageData["shop"] = shops
			jsonByte, _ := json.Marshal(&pageData)
			value := string(jsonByte)
			models.RDb.Set(key, value, time.Minute*10)

			c.Data["json"] = JsonR{
				Code: 200,
				Msg:  "查询成功-mysql",
				Data: pageData,
			}
			c.ServeJSON()
		}
	} else {
		json.Unmarshal([]byte(val), &pageData)
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "查询成功-redis",
			Data: pageData,
		}
		c.ServeJSON()
	}
}
